<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>金山文档编辑器</title>
    <meta name="referrer" content="never">
    <script>(function (){
        const tmp = window.location.origin+window.location.pathname;
        const sz = tmp.split("/");
        sz.length -= 4;
        const host = sz.join("/");
        window.kodSdkConfig = {api:host+"/"};
        document.write("<script src='"+host+"/static/app/dist/sdk.js'></"+"script>");
    })()</script>
    <script src="web-office-sdk-v1.1.19.umd.js"></script>
    <script src="sha1.min.js"></script>
    <script src="bignumber.min.js"></script>
    <script src="upload-aliyundrive.js"></script>
</head>
<body>
<div class="side-pane">
</div>
</body>
<script>
    (async function (){
        const param = new URL(window.location.href).searchParams;
        const path = param.get("path");
        const isEdit = !path.startsWith("{shareItemLink");
        let name = param.get("name");
        const webosUrl = localStorage.getItem("tenfellOffice_webosUrl");
        const aliPath = localStorage.getItem("tenfellOffice_aliPath");
        let wpsData = {};
        window.utils = {
            webosMethod:function (method,param){
                return fetch(webosUrl+"/"+method,{
                    method: 'POST',
                    body: JSON.stringify(param),
                    headers: {
                        "content-type":"application/json;charset=utf-8"
                    }
                }).then(function (res){
                    return res.json()
                });
            },
            uploadPre:function (p1,p2,p3){
                return this.webosMethod("uploadPre",{p1,p2,p3});
            },
            downloadUrl:function (p1){
                return this.webosMethod("downloadUrl",{p1});
            },
            uploadUrl:function (p1,p2,p3){
                return this.webosMethod("uploadUrl",{p1,p2,p3});
            },
            uploadAfter:function (p1,p2,p3){
                return this.webosMethod("uploadAfter",{p1,p2,p3});
            },
            getWpsUrl:function (p1,p2){
                return this.webosMethod("getWpsUrl",{p1,p2});
            },
            uuid:function (){
                function S4() {
                    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                }
                return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4();
            },
            ext:function (name){
                if(!name){
                    name = "";
                }
                let sz = name.split(".");
                if(sz.length>1){
                    return sz[sz.length-1].toLowerCase();
                }else{
                    return "";
                }
            },
            xhrReq:function (method,url,data,progress,headerMap,xhr,responseType){
                if(!xhr){
                    xhr = new XMLHttpRequest();
                }
                return new Promise(function (success,error){
                    xhr.open(method, url);
                    if(responseType){
                        xhr.responseType = responseType;
                    }
                    if(headerMap){
                        for(let key in headerMap){
                            let val = headerMap[key];
                            xhr.setRequestHeader(key,val);
                        }
                    }
                    xhr.addEventListener('loadend', function() {
                        if(xhr.readyState===4) {
                            success(xhr);
                        }
                    });
                    xhr.addEventListener('error', function() {
                        error();
                    });
                    xhr.addEventListener('progress', function(evt) {
                        if(progress){
                            progress(evt.loaded,evt.total,2);
                        }
                    });
                    xhr.upload.addEventListener('progress', function(evt) {
                        if(progress){
                            progress(evt.loaded,evt.total,1);
                        }
                    });
                    try{
                        xhr.send(data);
                    }catch (e){
                        error();
                    }
                });
            },
            getWpsIdByPath:async function (path,cache){
                if(cache){
                    const res = await fetch("api.php?type=1&path="+encodeURIComponent(path)).then(function (res){return res.json();});
                    if(res.flag){
                        return res.data;
                    }
                }
                return new Promise(async function (success,error){
                    const file = await fetch(parent.core.path2url(path)).then(function (res){return res.blob()});
                    const fileParam = {
                        status:1,
                        statusChange:function (res){
                            if(res.status == 2){
                                success(res.uploadPreRes.file_id);
                            }else{
                                success(false);
                            }
                        },
                        size:file.size,
                        fpSize:1024*1024*10,
                        file:file,
                        path:aliPath,
                        filePath:name
                    }
                    let fps = Math.floor(fileParam.size/fileParam.fpSize);
                    if(fileParam.size%fileParam.fpSize != 0){
                        fps ++;
                    };
                    fileParam.needFps = fps;
                    aliyundriveUpload.upload(fileParam,function (){});
                });
            },
            getWpsUrlByPath:async function (path){
                let fileId = await this.getWpsIdByPath(path,true);
                if(!fileId){
                    Tips.tips("文件上传失败,请重试","error");
                    return;
                }
                let res = await this.getWpsUrl(aliPath+"/"+fileId,isEdit);
                if(res.code != 0 || res.data.type == 0){
                    fileId = await this.getWpsIdByPath(path,false);
                    if(!fileId){
                        Tips.tips("文件上传失败,请重试","error");
                        return;
                    }
                    res = await this.getWpsUrl(aliPath+"/"+fileId,isEdit);
                    if(res.code != 0 || res.data.type == 0){
                        Tips.tips("获取预览地址失败","error");
                        return;
                    }
                }
                fetch("api.php?type=2&path="+encodeURIComponent(path)+"&file_id="+fileId);
                res.data.fileId = fileId;
                return res.data;
            },
            jsSdkInit:async function (url,token) {
                const that = this;
                if(that.jssdk){
                    await that.jssdk.destroy();
                }
                let jssdk = WebOfficeSDK.config({
                    commonOptions:{
                        isShowTopArea:true,
                        isShowHeader:true
                    },
                    url: url, // 该地址需要后端提供，https://wwo.wps.cn/office/p/xxx
                    commandBars: [
                        {
                            cmbId: 'HeaderLeft',
                            attributes: {
                                visible: false,
                                enable: false,
                            },
                        },
                        {
                            cmbId: 'HeaderRight',
                            attributes: {
                                visible: false,
                                enable: true,
                            },
                        },
                        {
                            cmbId: 'ShareLink',
                            attributes: {
                                visible: false,
                                enable: false,
                            },
                        },
                        {
                            cmbId: 'MobileHeader',
                            attributes: {
                                visible: false,
                                enable: false,
                            },
                        },
                    ],
                });
                jssdk.on('fileStatus', (v) => {
                    if(v.status == 7 || v.status == 1 || v.status == 4){
                        (async function () {
                            const res = await jssdk.save();
                            if(res.result == "ok"){
                                await utils.saveFile(wpsData.fileId,path);
                            }else{
                                if(res.result){
                                    var map = {
                                        "SpaceFull":"账号空间已满",
                                        "QueneFull":"保存中请勿频繁操作",
                                        "fail":"保存失败",
                                        "SavedEmptyFile":"空文件不支持保存"
                                    }
                                    if(map[res.result]){
                                    }
                                }else{
                                    Tips.tips("请尝试重新打开文档","error");
                                }
                            }
                        })();
                    }
                });
                if(token){
                    jssdk.setToken({
                        token: token
                    });
                }
                await jssdk.ready();
                that.jssdk = jssdk;
            },
            saveFile:async function (fileId, path) {
                const res = await utils.downloadUrl(aliPath+"/"+fileId);
                if(res.code != 0){
                    return false;
                }
                const blob = await fetch(res.data).then(function (res){
                    return res.blob();
                });
                return new Promise(function (success,error){
                    kodApi.fileSave(path,blob,function (res){
                        if(res && res.path){
                            success(true);
                        }else{
                            success(false);
                        }
                    });
                });
            }
        }
        name = utils.uuid()+"."+utils.ext(name);
        wpsData = await utils.getWpsUrlByPath(path);
        utils.jsSdkInit(wpsData.url,wpsData.token);
    })()
</script>
</html>